Last updated: 2024-04-03

Checks: 5 2

Knit directory: BITHub-preprocessing/

This reproducible R Markdown analysis was created with workflowr (version 1.7.1). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


The R Markdown file has unstaged changes. To know which version of the R Markdown file created these results, you’ll want to first commit it to the Git repo. If you’re still working on the analysis, you can ignore this warning. When you’re finished, you can run wflow_publish to commit the R Markdown file and build the HTML.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20230919) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Using absolute paths to the files within your workflowr project makes it difficult for you and others to run your code on a different machine. Change the absolute path(s) below to the suggested relative path(s) to make your code more reproducible.

absolute relative
/home/neuro/Documents/Brain_integrative_transcriptome/BITHub-preprocessing/data/metadata data/metadata

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 2f511ca. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rproj.user/
    Ignored:    output/Thesis_plots/Variance/PCA/BrainSpan/brainspan-varPart-cor/

Untracked files:
    Untracked:  code/preprocess/raw_file_locations.R

Unstaged changes:
    Deleted:    HDBR-PC-cor-filt.pdf
    Modified:   analysis/01-bulk-preprocess-data.Rmd
    Modified:   analysis/04-variation-drivers.Rmd
    Modified:   analysis/_site.yml
    Deleted:    cerebroViz_output_outer_1.svg
    Deleted:    cerebroViz_output_slice_1.svg
    Modified:   data/metadata/BrainSeq-metadata.csv

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/01-bulk-preprocess-data.Rmd) and HTML (docs/01-bulk-preprocess-data.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
html 2f511ca urwahnawaz 2024-04-02 Build site.
Rmd cb203cc urwahnawaz 2024-03-14 wflow_git_commit("./*")
html cb203cc urwahnawaz 2024-03-14 wflow_git_commit("./*")

Set-up

This R markdown document contains the complete code for the prep-rocessing of bulk RNA-sequencing files for Brain Integrative Transcriptome Hub (BITHub). All datasets were retrieved as described in Table 1 in the GitHub Repo.

In order to rerun the scripts - make sure to change the directories to the location of where the input files for pre-processing are stored. All directories are defined in code/preprocess/raw_file_locations.R. A copy of each processed metadata will also be saved in ’output/metadata/` for plotting purposes.

All other files are stored within the data folder of this R workflow directory.

library(recount3)
library(magrittr)
library(tibble)
library(reshape2)
library(SummarizedExperiment)
library(corrplot)
library(dplyr)
library(ggvenn)
library(pander)
library(gridExtra)
library(variancePartition)
library(DT)
library(EnsDb.Hsapiens.v86)
library(singscore)
library(AnnotationHub)
library(stargazer)
library(ggfortify)
library(glue)
library(cowplot)
library(broom)
library(glmpca)
library(DT)
library(naniar)
source("code/preprocess/functions.R")
source("code/preprocess/def_stages.R")
source("code/preprocess/raw_file_locations.R")
strc_acr <- map_df(structure_acronym, ~as.data.frame(.x), .id="id") %>% 
  set_colnames("StructureAcronym")
colnames(strc_acr)[2] = c("Structure")

rgns = map_df(regions, ~as.data.frame(.x), .id="id") %>% 
  set_colnames("Regions")
colnames(rgns)[2] = c("StructureAcronym")


rgns_ftl = map_df(regions_fetal, ~as.data.frame(.x), .id="id") %>% 
  set_colnames("Regions")
colnames(rgns_ftl)[2] = c("StructureAcronym")

Datasets to preprocess

BrainSeq

bseq.annot = read.csv(here::here("data/annotations/BrainSeq-metadata-annot.csv"), header = TRUE)
load(file.path(bseq, "rse_gene_unfiltered.Rdata"), envir = .GlobalEnv)
load(file.path(bseq,"methprop_pd.Rdata"), envir = .GlobalEnv)
x = rse_gene@colData 
x <- as.data.frame(x)
x <- as.data.frame(t(x))
replicated <- colnames(x)[grep(",", x["SAMPLE_ID",])]
y <- as.list(x)
y[replicated] <- lapply(y[replicated], function(z) {
  # which variables to merge
  to.weight <- which(sapply(z, length) > 1 & sapply(z, class) %in% c("numeric", "integer"))
  # weighting of the merge
  weighting <- z$numReads # total reads
  weighting <- weighting / sum(weighting) # rather than a straight average, it's based on the number of reads
  
  # apply weighting
  z[to.weight] <- lapply(z[to.weight], function(zz) {
    if (length(weighting) == length(zz)) {
      sum(weighting * zz)
      } else {
          NaN
        }
        
      })
      
      # quickly fix character variables
      char <- which(sapply(z, length) > 1 & sapply(z, class) == "character")
      z[char] <- lapply(z[char], function(zz) {
        paste(zz, collapse = " & ")
      })
      
      return(z)
    })
    
    w <- lapply(y, as.data.frame)
    w <- do.call("rbind", w)
    
    comp <- as.data.frame(pd)
    comp <- comp[,57:64]
    m <- match(rownames(comp), rownames(w)) # they are
    md<- cbind(w, comp[m,])
colnames(md) = bseq.annot$BITColumnName[match(colnames(md), bseq.annot$OriginalMetadataColumnName)]
    
    
    # Adding features 
md %<>% 
  rownames_to_column("SampleID") %>%
  mutate(Period = ifelse(.$AgeNumeric > 0, "Postnatal", "Prenatal"), 
                   StructureAcronym = gsub("HIPPO", "HIP", .$StructureAcronym),
                   Diagnosis = gsub("Schizo", "Schizophrenia", .$Diagnosis)) %>%
      mutate(Regions = add_feature(.$StructureAcronym, regions)) %>% 
      mutate(Age_rounded = as.character(sapply(na.omit(.$AgeNumeric), num_to_round))) %>% as.data.frame() %>%
      mutate(AgeInterval = as.character(add_feature(.$Age_rounded, age_intervals))) %>% 
      dplyr::select(-Age_rounded) %>%
      dplyr::select("SampleID", everything()) %>%
      as.data.frame()
md %>% 
  DT::datatable(caption = "BrainSeq Metadata after harmonizing column names, ages and structure acronyms")
exp = rse_gene@assays@.xData$data$rpkm
rownames(exp) <- sub("\\.[0-9]*$", "", rownames(exp))

Export

write.csv(exp, file = file.path(bseq.out, "BrainSeq-exp.csv"))
write.csv(md, file = file.path(bseq.out, "BrainSeq-metadata.csv"))
write.csv(md, file = file.path(here::here("data/metadata"), "BrainSeq-metadata.csv"))

BrainSpan

bspan.annot = read.csv(here::here("data/annotations/BrainSpan-metadata-annot.csv"), header = TRUE)

columns.metadata = read.csv(file.path(bspan, "columns_metadata.csv"), header = TRUE)
exp = read.csv(file.path(bspan, "expression_matrix.csv"), header= FALSE, row.names= 1)
rows.metadata = read.csv(file.path(bspan, "rows_metadata.csv"))
colnames(columns.metadata) = bspan.annot$BITColumnName[match(colnames(columns.metadata),bspan.annot$OriginalMetadataColumnName)]
md = columns.metadata %>% 
      mutate(Stage = add_feature(.$Age, stages), 
             AgeInterval = add_feature(.$Age, age_intervals), 
             Diagnosis = "Control", 
             Age = gsub(" ","_", .$Age)) %>%  
      mutate(SampleID = paste(DonorID, Age, StructureAcronym, Stage, sep = "_"), 
             age_for_mRIN = gsub("_", "", .$Age), 
             DonorName = gsub("\\.","_", .$DonorName),
            StructureAcronym = gsub("DFC", "DLPFC", StructureAcronym), 
            StructureAcronym = gsub("MFC", "ACC", StructureAcronym)) %>% 
  mutate(Regions = add_feature(.$StructureAcronym, regions)) %>%
      mutate('sample name' = paste(DonorName, age_for_mRIN,Sex ,StructureAcronym, sep = "//")) %>% 
      dplyr::select("SampleID", everything())

md$AgeNumeric[grepl("pcw", md$Age, ignore.case = TRUE)]<-
      md$Age[grepl("pcw", md$Age)] %>%  str_remove("_pcw")%>% 
      as.numeric() %>% `-` (40) %>% divide_by(52)
md$AgeNumeric[grepl("mos", md$Age, ignore.case = TRUE)] <- 
      md$Age[grepl("_mos", md$Age)] %>%  str_remove("_mos") %>% 
      as.numeric() %>% divide_by(12)
md$AgeNumeric[grepl("yrs", md$Age, ignore.case = TRUE)] <- 
      md$Age[grepl("_yrs", md$Age)] %>%  str_remove("_yrs") %>% 
      as.numeric 
    
md %<>% mutate(Period = ifelse(.$AgeNumeric >= 0, "Postnatal", "Prenatal"), 
                   colname = paste(DonorName, Age, StructureAcronym, sep = "_"))
colnames(exp) = md$SampleID
rownames(exp) <- rows.metadata$ensembl_gene_id
md.excel = read_excel(here::here("data/annotations/BrainSpan-additional.xlsx"),sheet =2, col_names = TRUE, skip =1) %>% 
      as.data.frame() %>% mutate_at(.vars = "AllenInstituteID", 
                                    .funs = gsub, pattern = "\\.", replacement = "\\_") %>%
      mutate_at(.vars = "Age", .funs = gsub, pattern = "PCW", replacement = "_pcw") %>% 
      mutate_at(.vars = "Age", .funs = gsub, pattern = "M", replacement = "_mos") %>%
      mutate_at(.vars = "Age", .funs = gsub, pattern = "Y", replacement = "_yrs") %>%
      mutate_at(.vars = "Region/Area", .funs = gsub, pattern = "\\/", replacement = "-") %>% 
      mutate(colname = paste(AllenInstituteID, Age, `Region/Area`, sep = "_")) %>% 
      dplyr::select(-c(Agerange, Age, Description))

md = md %>% 
      left_join(.,md.excel, by = "colname", keep = TRUE)
md.excel = read_excel(here::here("data/annotations/BrainSpan-additional.xlsx"), sheet = 1, col_names = TRUE) %>% 
      as.data.frame() %>% 
      mutate_at(.vars="Internal ID", .funs = gsub, pattern = "\\.", replacement = "\\_") %>% 
      dplyr::rename("Braincode" = "External ID")

md %<>% 
  left_join(md.excel, by ="Braincode") %>% 
      dplyr::select(-c("Age.y", "colname.y", "colname.x", "Gender", AllenInstituteID,
                     "Region/Area", "age_for_mRIN", "sample name", "Internal ID")) %>% 
      dplyr::rename("Ethnicity"="Ethn.")  %>% 
  distinct(SampleID, .keep_all = TRUE)


   
md = md[!duplicated(md[,c('column_num')]),]
md %<>% 
      dplyr::arrange(column_num)
md %>% 
  DT::datatable(caption = "BrainSpan metadata after metadata harmonization")

Export

write.csv(exp, file = file.path(bspan.out, "BrainSpan-exp.csv"))
write.csv(md, file = file.path(bspan.out,  "BrainSpan-metadata.csv"))
write.csv(md, file = file.path(here::here("data/metadata"), "BrainSpan-metadata.csv"))

GTEx

gtex.annot = read.csv(here::here("data/annotations/GTEx-metadata-annot.csv"), header = TRUE)
attributes = list.files(gtex, full.names = TRUE, pattern = "\\SampleAttributesDS.txt") # Sample attributes contains sample level information
phenotype = list.files(gtex, full.names = TRUE, pattern = "\\SubjectPhenotypesDS.txt") # Phenotype level information related to each donor 
exp = list.files(gtex, full.names = TRUE, pattern = "\\gene_tpm.gct.gz") # File used for expression matrix 
    
md.attrbutes = read_tsv(attributes, col_types = c('.default' = 'c')) %>% 
      dplyr::filter(SMTS == 'Brain') %>% 
      mutate(SUBJID = sapply(str_split(SAMPID, pattern = "-"), 
                             function(x) paste(x[1:2], collapse = '-'))) %>%
  left_join(read_tsv(phenotype, col_types = c('.default' = 'c')))  %>% 
  as.data.frame()
colnames(md.attrbutes) = gtex.annot$BITColumnName[match(colnames(md.attrbutes), gtex.annot$OriginalMetadataColumnName)]
    
 md.attrbutes %<>% 
  as.data.frame() %>% 
  mutate(StructureAcronym = add_feature(.$StructureAcronym, structure_acronym)) %>% 
      mutate(Regions = add_feature(.$StructureAcronym, regions), 
             AgeInterval = paste(.$AgeInterval, "yrs", sep = ""), 
             Diagnosis = "Control", 
             Sex = ifelse(Sex == 1, "M", "F"), 
             Period = "Postnatal") %>% as.data.frame()
    
exp = read.delim(exp, skip = 2)
colnames(exp) <- gsub("\\.", "-", colnames(exp)) # Changing expression file names to match metadata SampleIDs
exp %<>% column_to_rownames("Name")
    
exp = exp %>% 
      dplyr::select(contains(md.attrbutes$SampleID))
message(paste0("Samples subsetted - Exp matrix contains ", ncol(exp), " samples"))
rownames(exp) <- sub("\\.[0-9]*$", "", rownames(exp))
    
md.attrbutes= md.attrbutes[which(md.attrbutes$SampleID %in% colnames(exp)),] 
md.attrbutes %>% 
  DT::datatable(caption="GTEx metadata after preprocessing")

Export files

write.csv(exp, file = file.path(gtex.out, "GTEx-exp.csv"))
write.csv(md.attrbutes, file = file.path(gtex.out, "GTEx-metadata.csv"))
write.csv(md.attrbutes, file = file.path(here::here("data/metadata"), "GTEx-metadata.csv"))

Human developmental Biology Resource

Recount3 contains over 70,000 uniformly processed human RNA-seq samples. Recount provides gene, exon and exon-exon junction count matrices both in text format and as a RangedSummarizedExperiment.

The reads from recount were algined with the splice-aware Rail-RNA aligner. To compute the gene count matrices, the mapped reads were quantified with Gencode v25 with hg38 coordinates.

Unlike traditional quantification methods, recount3 provides base-pair coverage counts. Essentially, these are created in the following manner:

  • For each exonic base-pair, the number of reads overlapping at that given base pair is computed. However, as library size is provided in recount3, the coverage counts can be scaled to read counts for a given library size.
hdbr = recount3::create_rse_manual(
  project = "ERP016243",
  type = "gene"
)

hdbr_annot = read.csv(here::here("data/annotations/HDBR-metadata-annot.csv"), header=TRUE)
hdbr_supp = read_excel("/home/neuro/Documents/BrainData/Bulk/HDBR/Amended Supplementary Table 1.xlsx", 
                       sheet = 1, skip =6) %>% 
  as.data.frame()

colnames(hdbr_supp) = c("DonorID","Age", "SampleID", "Structure","Hemisphere", "Sex", "PMI")
hdbr_supp %<>% dplyr::select("DonorID","Structure", "PMI")
hdbr_phenotype = read.csv("/home/neuro/Documents/BrainData/Bulk/HDBR/hdbr-phenotype.csv", 
                          header=TRUE)
load(here::here("data/annotations/HDBR.Rda"))

md.hdbr = md.hdbr[,1:15]

colnames(md.hdbr) = hdbr_annot$BITColumnName[match(colnames(md.hdbr), hdbr_annot$OriginalMetadataColumnName)]

md.hdbr %<>% 
  as.data.frame() %>% 
  dplyr::select(-c(Block, OntologyIndividual,  KaryotypeOntology, Organism, OrganismOntology, 
                   StructureOntology, HemisphereOntology, OntologyAge)) %>% 
  mutate(AgeInterval = add_feature(.$Age, age_intervals))  %>%
  dplyr::rename("Structure"= "StructureAcronym") %>%
  left_join(strc_acr, by = "Structure") %>% 
  left_join(rgns_ftl, by = "StructureAcronym") %>% 
  mutate(Sex = toupper(Sex)) %>% 
  mutate(Sex = ifelse(str_detect(Sex,"XX"), "F",
                      ifelse(str_detect(Sex, "XY"), "M", "Unknown" )), 
         Diagnosis = c("Control"), 
         Period = c("Prenatal"))

md = colData(hdbr) %>% 
  as.data.frame() %>% 
   dplyr::select(-contains("2"))
colnames(md) = hdbr_annot$BITColumnName[match(colnames(md), hdbr_annot$OriginalMetadataColumnName)]

md.hdbr %<>%
  mutate(Hemisphere = gsub("right", "R", Hemisphere), 
         Hemisphere = gsub("left", "L", Hemisphere), 
         Hemisphere = gsub("frontal", "Frontal", Hemisphere))

hdbr_supp %<>% 
  distinct(DonorID, .keep_all = TRUE) %>% 
  mutate(PMI = ifelse(PMI == "UNKNOWN", NA, PMI))
md.hdbr %<>% 
  left_join(hdbr_supp, by = c("DonorID"))
full.md.hdbr =left_join(md.hdbr, md)
full.md.hdbr %<>%
  mutate(PMI = as.numeric(PMI))

full.md.hdbr %<>% 
  dplyr::filter(Structure.x != "stomach")
assay(hdbr, "counts") = transform_counts(hdbr, round = TRUE)

hdbr.tpm = recount::getTPM(hdbr)

filter <- rowSums(hdbr.tpm, na.rm = TRUE) > 0.05
hdbr.filter.tpm = hdbr.tpm[filter,]
hdbr.filter.tpm <- thresh(hdbr.filter.tpm)

Export data

hdbr.final = hdbr.tpm %>% 
  as.data.frame() %>% 
  dplyr::select(contains(full.md.hdbr$SampleID)) %>%
  rownames_to_column("EnsemblID") %>% 
  mutate_at(.vars = "EnsemblID", .funs = gsub, pattern = "\\.[0-9]*$", replacement = "") 

write.csv(hdbr.final, file =file.path(hdbr.out, "HDBR-exp.csv"))

write.csv(full.md.hdbr, file =file.path(hdbr.out, "HDBR-metadata.csv"))
write.csv(full.md.hdbr, file = file.path(here::here("data/metadata"), "HDBR-metadata.csv"))
full.md.hdbr %>% 
  DT::datatable(caption="HDBR metadata after harmonization")

PsychEncode

pe.annot = read.csv(here::here("data/annotations/PsychEncode-metadata-annot.csv"), header=TRUE)


exp = list.files(psych, full.names = TRUE, pattern = "\\Gene_expression_matrix_TPM.txt") %>% 
      read.table(., header=TRUE, row.names = 1, check.names = FALSE)
md = list.files(psych, full.names = TRUE, pattern = "Job*") %>% read.csv(., header=TRUE) %>% 
  dplyr::filter(individualID != "2015-1")
md.clinical = read.csv(file.path(psych, "PEC_capstone_data_map_clinical.csv"), header=TRUE, check.names = FALSE)
comp = list.files(psych, full.names = TRUE, pattern = "\\Cell_fractions*") %>% read_excel() %>%
      as.data.frame() %>% 
      column_to_rownames("CellType")
colnames(md) = pe.annot$BITColumnName[match(colnames(md), pe.annot$OriginalColumnName)]
    # Fix existing columns 
comp = comp[,-1] 
comp = as.data.frame(t(comp))
m <- match(md$SampleID, rownames(comp))
md <- cbind(md, comp[m,])

    
# PCW to age numeric 
md$AgeNumeric[grepl("PCW", md$AgeNumeric, ignore.case = TRUE)] = md$AgeNumeric[grepl("PCW", md$AgeNumeric)] %>%
  str_remove("PCW")%>% 
  as.numeric() %>% `-` (40) %>% divide_by(52)
    
md$AgeNumeric = gsub("90+", "91", md$AgeNumeric)
md$AgeNumeric =gsub("\\+", "", md$AgeNumeric)
    
    
md$AgeNumeric <- as.numeric(as.character(md$AgeNumeric))
    
md %<>%
      dplyr::filter(Diagnosis == "Affective Disorder" |
               Diagnosis == "Autism Spectrum Disorder" | 
               Diagnosis == "Bipolar Disorder" |
               Diagnosis == "Control" |
               Diagnosis == "Schizophrenia") %>% 
      mutate(Structure = c("Dorsolateral Prefrontal Cortex"),  ## Adding name of structure
             StructureAcronym = c("DLPFC")) %>%  
      mutate(Period = ifelse(.$AgeNumeric >= 0, "Postnatal", "Prenatal"))  %>%
      mutate(Age_rounded = as.character(sapply(.$AgeNumeric, num_to_round))) %>% as.data.frame() %>%
      mutate(AgeInterval = as.character(add_feature(.$Age_rounded, age_intervals)),
             Death = as.character(add_feature(.$causeDeath, death_cause))) %>% 
      mutate(Regions = c("Cortex")) %>% 
      mutate(DonorID = as.character(.$SampleID)) %>%
      dplyr::select(-Age_rounded) %>%
      as.data.frame()


exp = exp %>%
  dplyr::select(contains(md$SampleID))

md = md %>% 
  dplyr::filter(SampleID %in% colnames(exp))
exp = exp[colnames(exp) %in% md$SampleID,] 
md = md[md$SampleID %in% colnames(exp),] 

Export data

write.csv(exp, file = file.path(pe.out, "PsychEncode-exp.csv"))
write.csv(md, file = file.path(pe.out,"PsychEncode-metadata.csv"))
write.csv(md, file = file.path(here::here("data/metadata"), "PsychEncode-metadata.csv"))
rm(md)
rm(exp)

Exploring dataset attributes

summarise_stats = function(x, dataset)
{
    age = table(x$AgeInterval) %>% melt()
    age$Type = c(paste(dataset, "Sample", sep = "_"))
    individuals = x %>% group_by(AgeInterval, DonorID) %>% 
        dplyr::summarise(n = n()) %>% 
        as.data.frame() 
    individuals = table(individuals$AgeInterval) %>% melt()
    individuals$Type = c(paste("Individual", dataset, sep = "_"))
    
    age = rbind(age, individuals)
    colnames(age) = c("AgeInterval", "n", "Type")
    age$dataset = c(as.character(dataset))
    return(age)
    
}

summarise_regions = function(x, dataset){
    regions = x %>% 
        dplyr::group_by(AgeInterval, Regions) %>% 
        dplyr::summarise(n = n())  %>% 
        as.data.frame() %>% 
        mutate(Dataset = dataset)
    return(regions)
}
age_interval_stats = list()
directory = file.path("/home/neuro/Documents/Brain_integrative_transcriptome/BITHub-preprocessing/data/metadata")
pattern = "/home/neuro/Documents/Brain_integrative_transcriptome/BITHub-preprocessing/data/metadata/"

for (f in directory){
    md = list.files(f, full.names = TRUE, pattern = "\\-metadata.csv$")
    
    for (j in md){
        ct_file = read.csv(j, header= TRUE)
        dataset = gsub(pattern, "", j)
        dataset = gsub("\\-metadata.csv","", dataset)
        message("Now calculating statistics for ", dataset)
        stats = summarise_stats(ct_file, dataset)
        age_interval_stats[[paste(dataset)]] = stats
    }
    
}


bulk_plot_version2 = age_interval_stats %>% 
    do.call(rbind, .) %>% 
    mutate(AgeInterval = factor(AgeInterval, levels = c("4-7pcw", "8-9pcw",
                                                        "10-12pcw", "13-15pcw", "16-18pcw",
                                                        "19-24pcw", "25-38pcw", "0-5mos",
                                                        "6-18mos", "19mos-5yrs", "6-11yrs",
                                                        "12-19yrs", "20-29yrs", "30-39yrs", "40-49yrs",
                                                        "50-59yrs", "60-69yrs", "70-79yrs", "80-89yrs", "90-99yrs")), 
           Type = factor(Type, levels = c("BrainSeq_Sample", "Individual_BrainSeq",
                                          "BrainSpan_Sample", "Individual_BrainSpan",
                                          "GTEx_Sample", "Individual_GTEx", 
                                          "HDBR_Sample", "Individual_HDBR", 
                                          "Ramakar_Sample", "Individual_Ramakar",
                                          "PsychEncode_Sample", "Individual_PsychEncode"))) %>%
    drop_na() %>%
    ggplot(aes(x= AgeInterval, y = n, fill =Type)) +
    geom_bar(position = "dodge",stat= "identity") + 
    facet_grid(dataset~AgeInterval, scales = "free") + xlab("") + ylab("")  + theme_bw() +
    theme(legend.position = "none", axis.text.x=element_blank(),
          strip.background =element_rect(fill="#AA9A9C", color = "#E1DFDB"), 
          panel.border = element_rect(color = "#f7f4ed", fill = NA, size = 2)) + 
    theme(strip.text = element_text(colour = 'white')) +
    scale_fill_manual(values = c("#F75E5E", "#FFC6BD",
                                 "#49165E", "#EBBAFF",
                                 "#78A2EB", "#36466A",
                                 "#74C69D", "#2D6A4F",
                                 "#F9AD79", "#FF5F0F")) + 
    theme(
        panel.background = element_rect(fill = "transparent",colour = NA), # or theme_blank()
        plot.background = element_rect(fill = "transparent",colour =NA)
    )


bulk_plot_version2 

#ggsave(width = 11.01, height = 9.30, units = "in", 
 #      file = "../../Results/exploratory/bulk_dist_thesis.svg", plot = bulk_plot_version2)
#ggsave(file = "../../Results/exploratory/bulk_dist_update.svg", bulk_plot, 
 #      height = 18.9624, width = 45.3501, units = "cm")

sessionInfo()
R version 4.3.3 (2024-02-29)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 22.04.4 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.10.0 
LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0

locale:
 [1] LC_CTYPE=en_AU.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_AU.UTF-8        LC_COLLATE=en_AU.UTF-8    
 [5] LC_MONETARY=en_AU.UTF-8    LC_MESSAGES=en_AU.UTF-8   
 [7] LC_PAPER=en_AU.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_AU.UTF-8 LC_IDENTIFICATION=C       

time zone: Australia/Adelaide
tzcode source: system (glibc)

attached base packages:
 [1] tools     grid      stats4    stats     graphics  grDevices utils    
 [8] datasets  methods   base     

other attached packages:
 [1] lubridate_1.9.3             forcats_1.0.0              
 [3] purrr_1.0.2                 readr_2.1.5                
 [5] tidyverse_2.0.0             stringr_1.5.1              
 [7] tidyr_1.3.0                 scales_1.3.0               
 [9] data.table_1.14.10          readxl_1.4.3               
[11] naniar_1.0.0                glmpca_0.2.0               
[13] broom_1.0.5                 cowplot_1.1.2              
[15] glue_1.7.0                  ggfortify_0.4.16           
[17] stargazer_5.2.3             AnnotationHub_3.10.0       
[19] BiocFileCache_2.10.1        dbplyr_2.4.0               
[21] singscore_1.22.0            EnsDb.Hsapiens.v86_2.99.0  
[23] ensembldb_2.26.0            AnnotationFilter_1.26.0    
[25] GenomicFeatures_1.54.1      AnnotationDbi_1.64.1       
[27] DT_0.31                     variancePartition_1.32.2   
[29] BiocParallel_1.36.0         limma_3.58.1               
[31] gridExtra_2.3               pander_0.6.5               
[33] ggvenn_0.1.10               ggplot2_3.4.4              
[35] dplyr_1.1.4                 corrplot_0.92              
[37] reshape2_1.4.4              tibble_3.2.1               
[39] magrittr_2.0.3              recount3_1.12.0            
[41] SummarizedExperiment_1.32.0 Biobase_2.62.0             
[43] GenomicRanges_1.54.1        GenomeInfoDb_1.38.5        
[45] IRanges_2.36.0              S4Vectors_0.40.2           
[47] BiocGenerics_0.48.1         MatrixGenerics_1.14.0      
[49] matrixStats_1.2.0           workflowr_1.7.1            

loaded via a namespace (and not attached):
  [1] fs_1.6.3                      ProtGenerics_1.34.0          
  [3] bitops_1.0-7                  httr_1.4.7                   
  [5] numDeriv_2016.8-1.1           doRNG_1.8.6                  
  [7] backports_1.4.1               utf8_1.2.4                   
  [9] R6_2.5.1                      lazyeval_0.2.2               
 [11] withr_3.0.0                   prettyunits_1.2.0            
 [13] cli_3.6.2                     labeling_0.4.3               
 [15] sass_0.4.8                    mvtnorm_1.2-4                
 [17] recount_1.28.0                Rsamtools_2.18.0             
 [19] foreign_0.8-86                R.utils_2.12.3               
 [21] rentrez_1.2.3                 sessioninfo_1.2.2            
 [23] BSgenome_1.70.1               rstudioapi_0.15.0            
 [25] RSQLite_2.3.5                 generics_0.1.3               
 [27] BiocIO_1.12.0                 gtools_3.9.5                 
 [29] crosstalk_1.2.1               vroom_1.6.5                  
 [31] Matrix_1.6-5                  fansi_1.0.6                  
 [33] abind_1.4-5                   R.methodsS3_1.8.2            
 [35] lifecycle_1.0.4               whisker_0.4.1                
 [37] yaml_2.3.8                    edgeR_4.0.11                 
 [39] qvalue_2.34.0                 gplots_3.1.3                 
 [41] SparseArray_1.2.3             blob_1.2.4                   
 [43] promises_1.2.1                crayon_1.5.2                 
 [45] lattice_0.22-5                annotate_1.80.0              
 [47] KEGGREST_1.42.0               pillar_1.9.0                 
 [49] knitr_1.45                    rjson_0.2.21                 
 [51] boot_1.3-28.1                 corpcor_1.6.10               
 [53] codetools_0.2-19              getPass_0.2-4                
 [55] downloader_0.4                vctrs_0.6.5                  
 [57] png_0.1-8                     Rdpack_2.6                   
 [59] cellranger_1.1.0              gtable_0.3.4                 
 [61] cachem_1.0.8                  xfun_0.41                    
 [63] rbibutils_2.2.16              S4Arrays_1.2.0               
 [65] mime_0.12                     iterators_1.0.14             
 [67] statmod_1.5.0                 interactiveDisplayBase_1.40.0
 [69] ellipsis_0.3.2                nlme_3.1-164                 
 [71] pbkrtest_0.5.2                bit64_4.0.5                  
 [73] progress_1.2.3                EnvStats_2.8.1               
 [75] filelock_1.0.3                rprojroot_2.0.4              
 [77] GenomicFiles_1.38.0           bslib_0.6.1                  
 [79] rpart_4.1.23                  KernSmooth_2.23-22           
 [81] Hmisc_5.1-1                   colorspace_2.1-0             
 [83] DBI_1.2.1                     nnet_7.3-19                  
 [85] tidyselect_1.2.0              processx_3.8.3               
 [87] bit_4.0.5                     compiler_4.3.3               
 [89] curl_5.2.0                    git2r_0.33.0                 
 [91] graph_1.80.0                  htmlTable_2.4.2              
 [93] derfinder_1.36.0              xml2_1.3.6                   
 [95] DelayedArray_0.28.0           rtracklayer_1.62.0           
 [97] checkmate_2.3.1               caTools_1.18.2               
 [99] remaCor_0.0.16                callr_3.7.3                  
[101] rappdirs_0.3.3                digest_0.6.34                
[103] minqa_1.2.6                   rmarkdown_2.25               
[105] GEOquery_2.70.0               aod_1.3.3                    
[107] XVector_0.42.0                RhpcBLASctl_0.23-42          
[109] base64enc_0.1-3               htmltools_0.5.7              
[111] pkgconfig_2.0.3               lme4_1.1-35.1                
[113] highr_0.10                    fastmap_1.1.1                
[115] rlang_1.1.3                   htmlwidgets_1.6.4            
[117] shiny_1.8.0                   farver_2.1.1                 
[119] jquerylib_0.1.4               jsonlite_1.8.8               
[121] R.oo_1.25.0                   VariantAnnotation_1.48.1     
[123] RCurl_1.98-1.14               Formula_1.2-5                
[125] GenomeInfoDbData_1.2.11       munsell_0.5.0                
[127] Rcpp_1.0.12                   visdat_0.6.0                 
[129] stringi_1.8.3                 zlibbioc_1.48.0              
[131] MASS_7.3-60.0.1               bumphunter_1.44.0            
[133] plyr_1.8.9                    parallel_4.3.3               
[135] Biostrings_2.70.1             splines_4.3.3                
[137] hms_1.1.3                     derfinderHelper_1.36.0       
[139] locfit_1.5-9.8                ps_1.7.6                     
[141] rngtools_1.5.2                biomaRt_2.58.0               
[143] BiocVersion_3.18.1            XML_3.99-0.16                
[145] evaluate_0.23                 BiocManager_1.30.22          
[147] foreach_1.5.2                 nloptr_2.0.3                 
[149] tzdb_0.4.0                    httpuv_1.6.13                
[151] xtable_1.8-4                  restfulr_0.0.15              
[153] fANCOVA_0.6-1                 later_1.3.2                  
[155] lmerTest_3.1-3                memoise_2.0.1                
[157] GenomicAlignments_1.38.2      cluster_2.1.6                
[159] timechange_0.3.0              GSEABase_1.64.0              
[161] here_1.0.1